package se.webbzon.oschi01.json;

import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class JsonObject implements JsonType, Map<JsonLeaf<String>,JsonType> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 8563062943353487496L;
	
	protected final Map<JsonLeaf<String>,JsonType> map = new HashMap<JsonLeaf<String>,JsonType>();
	
	public JsonObject() {}
	
	public JsonObject(JsonObject other) {
		for (Entry<JsonLeaf<String>,JsonType> entry : other.map.entrySet()) {
			map.put(entry.getKey().clone(), entry.getValue().clone());
		}
	}

	@Override public Type getType() {
		return JsonType.Type.Object;
	}
	
	@Override public String toString() {
		StringBuilder builder = new StringBuilder("{");
		boolean first = true;
		for (Entry<JsonLeaf<String>,JsonType> entry : map.entrySet()) {
			if (first)
				first = false;
			else
				builder.append(",");
			builder.append(entry.getKey().toString());
			builder.append(":");
			builder.append(entry.getValue().toString());
		}
		builder.append("}");
		return builder.toString();
	}
	
	@Override public int hashCode() {
		int hashCode = 0;
		for (Entry<JsonLeaf<String>,JsonType> entry : map.entrySet()) {
			hashCode += entry.getKey().hashCode() + entry.getValue().hashCode();
		}
		return hashCode;
	}

	@Override public JsonType clone() {
		return new JsonObject(this);
	}

	@Override public void clear() {
		map.clear();
	}

	@Override public boolean containsKey(Object key) {
		return map.containsKey(key);
	}

	@Override public boolean containsValue(Object value) {
		return map.containsKey(value);
	}

	@Override public Set<java.util.Map.Entry<JsonLeaf<String>, JsonType>> entrySet() {
		return map.entrySet();
	}

	@Override public JsonType get(Object key) {
		return map.get(key);
	}

	@Override public boolean isEmpty() {
		return map.isEmpty();
	}

	@Override public Set<JsonLeaf<String>> keySet() {
		return map.keySet();
	}

	@Override public JsonType put(JsonLeaf<String> key, JsonType value) {
		return map.put(key, value);
	}

	@Override public void putAll(Map<? extends JsonLeaf<String>, ? extends JsonType> m) {
		map.putAll(m);
	}

	@Override public JsonType remove(Object key) {
		return map.remove(key);
	}

	@Override public int size() {
		return map.size();
	}

	@Override public Collection<JsonType> values() {
		return map.values();
	}

	@Override public void printTo(PrintStream ps) throws IOException {
		ps.print("{");
		boolean first = true;
		for (Entry<JsonLeaf<String>,JsonType> entry : map.entrySet()) {
			if (first)
				first = false;
			else
				ps.print(",");
			entry.getKey().printTo(ps);
			ps.print(":");
			entry.getValue().printTo(ps);
		}
		ps.print("}");
	}

}
